#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include<string.h>
#include <arpa/inet.h>
#include<unistd.h>
#include <netinet/in.h>
const int backlog = 10;
enum ERROR_NUM
{
    SOCK_ERR = 2,
    BIND_ERR,
    LISTEN_ERR
};
class Sock
{
public:
    Sock()
    {
    }
    ~Sock()
    {
    }
    void Socket()
    {
        _sockfd = socket(AF_INET,SOCK_STREAM,0);
        if(_sockfd < 0)
        {
            std::cerr<<"create socket error!"<<std::endl;
            exit(SOCK_ERR);
        }
        std::cout<<"socket success!"<<std::endl;
    }
    void Bind(uint16_t port)
    {
        int opt;
        setsockopt(_sockfd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
        struct sockaddr_in local;
        memset(&local,0,sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;

        int n = bind(_sockfd,(struct sockaddr*)&local,sizeof(local));
        if(n == -1)
        {
            std::cerr<<"bind socket error!"<<std::endl;
            exit(BIND_ERR);
        }
        std::cout<<"bind success!"<<std::endl;
    }
    void Listen()
    {
        std::cout<<"_sockfd:"<<_sockfd<<std::endl;
        int n = listen(_sockfd,backlog);
        if(n == -1)
        {
            std::cerr<<"listen socket error!"<<std::endl;
            exit(LISTEN_ERR);
        }
        std::cout<<"listen success!"<<std::endl;
    }
    int Accept(std::string* clientip,uint16_t* clientport)
    {
        //!accept函数用于从处于监听状态的套接字接受客户端的连接请求，并创建一个新的套接字来与客户端进行通信。
        //*用于存储客户端的地址信息
        struct sockaddr_in peer;
        socklen_t len = sizeof peer;
        int newsockfd = accept(_sockfd,(struct sockaddr*)&peer,&len);
        if(newsockfd < 0)
        {
            std::cerr<<"accept socket error!"<<std::endl;
            return -1;
        }   
        char ipstr[64];
        inet_ntop(AF_INET,&peer.sin_addr,ipstr,INET_ADDRSTRLEN);
        *clientip = ipstr;
        *clientport = ntohs(peer.sin_port);
        return newsockfd;
    }

    bool Connect(const std::string& ip,const uint16_t& port)
    {
        struct sockaddr_in peer;
        memset(&peer,0,sizeof peer);
        peer.sin_family = AF_INET;
        peer.sin_port = htons(port);
        //将点分十进制的字符串形式ip转换成为网络字节序的二进制格式
        inet_pton(AF_INET,ip.c_str(),&peer.sin_family);
        int n = connect(_sockfd,(struct sockaddr*)&peer,sizeof(peer));
        if(n < 0)
        {
            std::cerr<<"connect socket error!"<<std::endl;
            return false;
        }
        return true;
    }
    int Sockfd()
    {
        return _sockfd;
    }

private:
    int _sockfd;
};